#define _SHARED_FUNC
#include "pasting.h"
#include <fcntl.h>

int
connexion_tcp (char *serv, int port)
{
  SOCKADDR_IN SinDist;
  int sock;
  unsigned long oldopt;

  sock = socket (AF_INET, SOCK_STREAM, 0);
  if (sock == -1)
    {
      perror ("socket");
      return sock;
    }
  SinDist.sin_family = AF_INET;
  SinDist.sin_addr.s_addr = inet_addr (serv);
  SinDist.sin_port = htons (port);

  if (SinDist.sin_addr.s_addr == -1)
    return -1;


#ifdef WIN32
  oldopt = 1;
  ioctlsocket (sock, FIONBIO, &oldopt);
#else
  oldopt = fcntl (sock, F_GETFL);
  fcntl (sock, F_SETFL, O_NONBLOCK);
#endif

  connect (sock, (struct sockaddr *) &SinDist, sizeof (SOCKADDR_IN));

#ifdef WIN32
  oldopt = 0;
  ioctlsocket (sock, FIONBIO, &oldopt);
#else
  fcntl (sock, F_SETFL, oldopt & ~O_NONBLOCK);
#endif

  return sock;
}

int
data_in_wait (int sock)
{
  fd_set drop;
  struct timeval temps;

  FD_ZERO (&drop);
  FD_SET (sock, &drop);

  temps.tv_sec = 0;
  temps.tv_usec = 10;

  select (sock + 1, &drop, NULL, NULL, &temps);
  if (FD_ISSET (sock, &drop))
    return 1;

  return 0;
}

int
reception_tcp (dcclist * dc)
{
  char *data;
  unsigned int len;

  if (data_in_wait (dc->sock))
    {
      data = (char *) malloc (1501);
      len = recv (dc->sock, data, 1500, 0);
      if (len <= 0)
	return 0;
      *(data + len) = 0;
      dc->current_len += len;
      fputs (data, dc->dfile);
      len = htonl (dc->current_len);
      send (dc->sock, (char *) &len, 4, 0);
      free (data);
    }
  return 1;
}
